package com.piece.core.framework.util.basic;

import com.piece.core.framework.util.string.StringUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Setter
public class ConfigUtil {

    private final static ReentrantLock lock = new ReentrantLock();
    private final static Environment environment = (Environment) SpringUtil.getBean("environment");

    private String active;
    private static ConfigUtil instance;

    public static ConfigUtil getInstance() {
        if (null == instance) {
            lock.lock();
            if (null == instance) {
                instance = new ConfigUtil();
                instance.setActive(environment.getProperty("spring.profiles.active"));
            }
            lock.unlock();
        }

        return instance;
    }

    /**
     * 根据key获取Spring boot配置文件中的值
     */
    public String get(String key) {
        return environment.getProperty(key);
    }

    /**
     * 根据配置文件名和key读取配置文件的value
     */
    public String getPropertyVal(String pro, String key) {
        String ext = ".properties";
        if (StringUtil.isNotEmpty(active)) {
            ext = "_" + active + ".properties";
        }

        ClassPathResource resource = new ClassPathResource("conf/" + pro + ext);
        InputStream in;
        Properties props = new Properties();
        try {
            in = resource.getInputStream();
            if (null == in) {
                resource = new ClassPathResource("conf/" + pro + ".properties");
                in = resource.getInputStream();
            }
            props.load(in);
        } catch (IOException e) {
            log.error("加载配置[{}]文件出错", "conf/" + pro + ext, e);
        }
        return props.getProperty(key).trim();
    }
}
